import React,{useEffect,useState} from 'react'
import {useSelector} from 'react-redux'  
import { Space,Switch, Table,Button,Tabs ,message, Popconfirm} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TabsProps } from 'antd';
import $axios,{ImgUrl} from '../../utils/axios'
import SearchInfo from '../../components/SearchInfo';
import AddTeam from './teamItem/AddTeam';
import TeamDetail from './teamItem/TeamDetail';

interface DataType {
  id:string;
  number: string;
  name: string;
  picture: string;
  manageName: string;
  organName: string;
  shareCount: string;
  score: string;
  status: string;
  
}
interface OrganDataType {
  value:string;
  label:string;
}

export default function Team() {
    // 表格
    const columns: ColumnsType<DataType> = [
      {
        title: '编号',
        dataIndex: 'number',
        key: 'number',
        width:130,
      },
      {
        title: '头像',
        dataIndex: 'picture',
        key: 'picture',
        width:100,
        render: (_, { picture }:any) => <img src={ImgUrl+picture} alt="" style={{width:'60px',height:'60px'}} />,
      },
      {
        title: '团队名称',
        dataIndex: 'name',
        key: 'name',
        width:90,
      },
      {
        title: '团队长',
        dataIndex: 'manageName',
        key: 'manageName',
        width:90,
      },
      {
        title: '所属机构',
        dataIndex: 'organName',
        key: 'organName',
        width:300,
      },
      {
        title: '分享量',
        dataIndex: 'shareCount',
        key: 'shareCount',
        width:90,
      },
      {
        title: '评分',
        dataIndex: 'score',
        key: 'score',
        width:80,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width:80,
        render: (_, { status }:any) => (
          <Switch checkedChildren="启用" unCheckedChildren="关闭" defaultChecked={status==1?true:false}   />
        ),
      },
      
      {
        title: '操作',
        key: 'action',
        render: (_, { id }:any) => (
          <Space >
           <Button type="text" size='small' onClick={()=>LooKDetail(id)}>查看详情</Button>
           <Popconfirm
              title="解散确认"
              description="确定解散此团队吗？?"
              onConfirm={()=>confirm(id)}
              okText="是"
              cancelText="否"
            >
              <Button type="text" size='small' danger >解散团队</Button>
            </Popconfirm>
           
          </Space>
        ),
      },
    ];
    // =====
    const [defaultView,setDefaultView]=useState(true)
    const [addView,setAddView]=useState(false)
    const [lookView,setLookView]=useState(false)
    const [teamID,setTeamID]=useState('')
    const [organData,setOrganData] =  useState<OrganDataType[]>([]) //机构数据
  const [idList,setIdList] = useState<any>()
  const [team,setTeam] = useState<any>([])
  const [showList,setShowList] = useState<any>()
  const doctorInfo = useSelector((state:any)=>{ // 仓库获取医生
    return state.task.doctorInfo  //全部信息 
 })
 useEffect(()=>{
  setAddView(false)
  setDefaultView(true)
 },[])
 useEffect(()=>{

  getDoctorTeamOrgById()
  getOrganData()
 },[doctorInfo.id])

//  根据id查询医生相关团队以及所属机构 /api/getDoctorTeamOrgById
const getDoctorTeamOrgById=()=>{
  $axios({
    url:'/api/getDoctorTeamOrgById',
    method:'post',
    data:{
      id:doctorInfo.id
    }
  }).then((res:any)=>{
    console.log(res,8998989);
    for (const key in res.data.teamListM) {
     if(res.data.teamListM[key].id){
      getTOSSMLById(res.data.teamListM[key].id)
     }
    }
    setIdList(res.data)
    setShowList(res.data.teamListM)
  })
}
// 根据id查询团队，机构，签约人数，团队长，团队标签 /api/getTOSSMLById
const getTOSSMLById=(id:any)=>{
  if(id){
    $axios({
      url:'/api/getTOSSMLById',
      method:'post',
      data:{
        id
      }
    }).then((res:any)=>{
      console.log(res,'团队');
      let data = {} as DataType
      data.id= res.data.team.id
      data.number=  res.data.team.number
      data.name= res.data.team.name
      data.picture=  res.data.team.picture
      data.manageName=  res.data.manage?.name
      data.organName=  res.data.organ.name
      data.shareCount=  res.data.team.shareCount
      data.score=  res.data.team.score
      data.status=  res.data.team.status
      let newArr = team
      newArr.push(data)
      console.log(newArr,'1');
      setTeam([...newArr])
      // setShowList(res.data.teamListM)
    })
  }
}

// 选择
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
  console.log('selectedRowKeys changed: ', newSelectedRowKeys);
  setSelectedRowKeys(newSelectedRowKeys);
};

const rowSelection = {
  selectedRowKeys,
  onChange: onSelectChange,
};
// 标签卡切换
const onChange = (key: string) => {
  console.log(key);
  if(key=='1'){
    setTeam([])
    for (const key in idList.teamListM) { 
      getTOSSMLById(idList.teamListM[key].id)
    }
  }else{
    setTeam([])
    for (const key in idList.teamList) {
      getTOSSMLById(idList.teamList[key].id)
    }
  }
};
const items: TabsProps['items'] = [
  {
    key: '1',
    label: `我管理的团队`,
    children:   <Table columns={columns} rowSelection={rowSelection} dataSource={team}  size="small" rowKey='id' scroll={{ y: 500 }} />,
  },
  {
    key: '2',
    label: `我加入的团队`,
    children: <Table columns={columns} rowSelection={rowSelection} dataSource={team}  size="small" rowKey='id' scroll={{ y: 500 }} />,
  }
];
    // 删除团队
    const confirm = (id:any) => {
      delTeamOne(id)
    };
    const delTeamOne=(id:any)=>{
      $axios({
        url:'/api/delTeamById',
        method:'post',
        data:{
          id
        }
      }).then((res:any)=>{
        console.log(res);
        if(res.code==200){
          message.success('删除成功');
          getDoctorTeamOrgById()
        }else{
          message.error('删除失败');
        }
      })
    }
      // 获取机构数据
    const getOrganData =()=>{
      $axios({
        url:'/api/getAllChcsOrgan',
        method:'post',
      }).then((res:any)=>{
        console.log(res.data.rows);
        let newData = [] as OrganDataType[]
        res.data.rows.map((i:any)=>{
          let obj = {
            value:i.id,
            label:i.name
          }
          newData.push(obj)
        })
        setOrganData([...newData])
      })
    }

  // 搜索
  const searchColoms = [
    {
      type:'select',
      label:'所属机构',
      name:'organId',
      options:organData
    },
    {
      type:'text',
      name:'name',
    },
    {
      type:'button',
      name:'button',
    }
    
  ]
  const goSearch=(value:any)=>{
    console.log(value,'父组件');
    $axios({
      url:'/api/getTeamByOrganId',
      method:'post',
      data:{
        organId:value.organId
      }
    }).then((res:any)=>{
      console.log(res);
      
      
    })

  }

  // 查看详情
  const LooKDetail=(id:any)=>{
    setTeamID(id)
    setLookView(true)
    setAddView(false)
    setDefaultView(false)
  }
  // 新增团队
  const showAddTeam=()=>{
    setAddView(true)
    setDefaultView(false)
  }
  //   返回
  const back=()=>{
    setDefaultView(true)
    setAddView(false)
    setLookView(false)

    getDoctorTeamOrgById()
    getOrganData()
    setTeam([])
    for (const key in idList.teamListM) { 
      getTOSSMLById(idList.teamListM[key].id)
    }
    
  }
 
  return (
    <div>

      {
        defaultView&&<>
                    {
                      organData.length>0&&<SearchInfo coloms={searchColoms} click={(value:any)=>goSearch(value)} rowKey='name'></SearchInfo>
                    }
                    <Button type="primary" onClick={showAddTeam}>新增团队</Button>
                    <Tabs  defaultActiveKey="1" items={items} onChange={onChange} />
                    </>
      }
      {
        addView&&<AddTeam back={back}/>
      }
      {
        lookView&&<TeamDetail id={teamID} back={back}/>
      }
    </div>
  )
}
